package com.unis.common.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by pure on 2018-05-06.
 * 动态切换数据源
 */
public class DataSourceContextHolder {
    /**
     * 默认数据源
     */
    public static final String DEFAULT_DS = "datasource1";

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();

    private static final Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);


    // 设置数据源名
    public static void setDB(String dbType) {
        logger.info("切换到{"+dbType+"}数据源");
        contextHolder.set(dbType);
    }

    // 获取数据源名
    public static String getDB() {
        //return (contextHolder.get());
        if(contextHolder.get()==null){
            return DEFAULT_DS;
        }else{
            return (contextHolder.get());
        }
    }

    // 清除数据源名
    public static void clearDB() {
        contextHolder.remove();
    }
}
